<template>
  <div class="product-desc">
    <!-- <i class="topbar"></i> -->

    <section class="desc">
      <div class="title">
        <div>商品描述</div>
        <div>
          <span class="font" :class="{ over: desc.length > 2000 }">{{ desc.length }}</span>
          /2000
        </div>
      </div>

      <div class="content">
        <nut-textarea v-model="desc" placeholder="请输入商品描述" autosize max-length="2000" />
      </div>
    </section>

    <section class="image">
      <div class="title">商品图片</div>

      <div class="content">
        <template v-for="(item, index) in imageList" :key="item">
          <div class="img-item">
            <img class="img" :src="commonStore.img_domain + item" />
            <img class="close" src="@/assets/icons/close.png" @click="handleDelImg(index)" />
          </div>
        </template>

        <nut-uploader
          url="#"
          accept="image/*"
          :before-upload="beforeUpload"
          v-show="imageList.length < 3"
        ></nut-uploader>
      </div>

      <div class="tip">一次最多可以上传三张图片</div>
    </section>

    <section class="action" :class="{ toolman: isIOS }">
      <button class="btn" @click="handleSave">保存</button>
    </section>
  </div>
</template>

<script lang="ts" setup>
  import _ from 'lodash'
  import useCommonStore from '@/store/common'
  import { judgeClient } from '@/utils/utils'
  import { useRoute, useRouter } from 'vue-router'
  import { uploadImgApi, getOSTokenApi } from '@/api/addstart'
  import { getClient, ossPath } from '@/utils/alioss'
  import { ref, onActivated } from 'vue'
  const { isIOS } = judgeClient()


  // ------ router
  const router = useRouter()
  const route = useRoute()

  // ------- store
  const commonStore = useCommonStore()

  // ------ data
  const desc = ref('')
  const imageList = ref<any[]>([])
  const credentials = ref<any>({
    securityToken: '',
    accessKeySecret: '',
    accessKeyId: ''
  })

  // ------ methods
  const beforeUpload = (fileList: File[]) => {
    // uploadImg(fileList[0])
    uploadOSS(fileList[0], 'image')

    return new Promise((resolve) => {
      resolve(fileList)
    })
  }
  const handleSave = () => {
    const payload = {
      id: route.query.id,
      desc: desc.value,
      imageList: [...imageList.value]
    }
    window.localStorage.setItem(`productDesc-${route.query.id}`, JSON.stringify(payload))

    router.back()
  }
  const handleDelImg = (index: any) => {
    imageList.value.splice(index, 1)
  }

  // ------ request
  // 接口：上传图片
  async function uploadImg(imgfile: File) {
    const res = await uploadImgApi({ imgfile })
    if (res.code == 0) {
      const { img_key } = res.result
      imageList.value.push(img_key)
    }
  }
  // 接口：获取OSS Token
  async function getOSSToken() {
    const res = await getOSTokenApi()
    if (res.code == 0) {
      const { accessKeyId, accessKeySecret, securityToken } = res.result.credentials
      credentials.value.accessKeyId = accessKeyId
      credentials.value.accessKeySecret = accessKeySecret
      credentials.value.securityToken = securityToken
    }
  }
  async function uploadOSS(file: any, fileType: any) {
    var imgUrl = ossPath(file, fileType)
    getClient(
      credentials.value.accessKeyId,
      credentials.value.accessKeySecret,
      credentials.value.securityToken
    )
      .multipartUpload(imgUrl, file)
      .then((res: any) => {
        if (res.res.statusCode == 200) {
          var pathurl = res.name.replace('image/', '')
          imageList.value.push(pathurl)
        }
      })
  }

  // ------ lifecycle
  function setupInit() {
    const localProductDesc = window.localStorage.getItem(`productDesc-${route.query.id}`)
    if (localProductDesc) {
      const productDesc = JSON.parse(localProductDesc)
      desc.value = productDesc.desc
      imageList.value = _.cloneDeep(productDesc.imageList)
    }

    getOSSToken()
  }
  setupInit()
</script>

<style lang="scss" scoped>
  .product-desc {
    display: flex;
    flex-direction: column;
    height: 100vh;
    overflow: auto;
    background: #ffffff;

    .topbar {
      display: block;
      width: 100%;
      height: 20px;
      background: #f8f9fa;
    }

    .desc {
      box-sizing: border-box;
      padding: 0 30px;

      .title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 100px;
        border-bottom: 1px solid #eeeeee;

        div:first-of-type {
          font-size: 32px;
          font-family: PingFang-SC-Medium, PingFang-SC;
          font-weight: 500;
          color: #000000;
        }
        div:last-of-type {
          font-size: 24px;
          font-family: PingFang-SC-Regular, PingFang-SC;
          font-weight: 400;
          color: #999999;
        }

        .over {
          color: red;
        }
      }

      .content {
        min-height: 414px;
        border-bottom: 1px solid #eeeeee;

        :deep(.nut-textarea) {
          padding: 30px 0;

          .nut-textarea__textarea {
            min-height: 414px;
          }
        }
      }
    }

    .image {
      box-sizing: border-box;
      padding: 0 30px;

      .title {
        display: flex;
        align-items: center;
        height: 100px;
        font-size: 32px;
        font-family: PingFang-SC-Medium, PingFang-SC;
        font-weight: 500;
        color: #000000;
      }

      .content {
        display: flex;
        flex-wrap: wrap;

        .img-item {
          position: relative;
          margin: 0 20px 20px 0;
          width: 30%;

          .img {
            display: block;
            width: 100%;
            height: 210px;
          }

          .close {
            position: absolute;
            top: -8px;
            right: -8px;
            width: 36px;
          }
        }
      }

      .tip {
        font-size: 24px;
        font-family: PingFang-SC-Regular, PingFang-SC;
        font-weight: 400;
        color: #999999;
        margin-top: 30px;
      }
    }

    .action {
      position: absolute;
      left: 0;
      bottom: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 120px;

      .btn {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 630px;
        height: 90px;
        background: linear-gradient(90deg, #3ebd33 0%, #9fdf4f 100%);
        box-shadow: 0px 10px 20px 0px rgba(105, 194, 97, 0.27);
        border: none;
        border-radius: 45px;
        font-size: 30px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #ffffff;
      }
    }

    .toolman {
      padding-bottom: 68px;
    }
  }
</style>
